<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>

    var dragEle = {
        target: document.getElementsByClassName('box')[0],
        posX: null,
        posY: null,
        dragStart: function () {
            this.dragDown()
        },
        dragEnd: function () {
            this.target.onmousedown = null
        },
        dragDown: function () {
            //使用ES6的箭头函数,this向上一级寻找，this指向dragEle,否则指向绑定事件的元素对象
            this.target.onmousedown = e => {
                this.posX = e.offsetX
                this.posY = e.offsetY
                this.dragMove()
                this.dragUp()
            }
        },
        dragMove: function () {
            document.onmousemove = e => {
                var e = e || window.event
                var x = e.pageX - this.posX
                var y = e.pageY - this.posY
                this.target.style.left = x + "px"
                this.target.style.top = y + "px"
            }
        },
        dragUp: function () {
            document.onmouseup = () => {
                document.onmousemove = null
                document.onmouseup = null
            }
        }
    }

    new Promise((res, rej) => {
        dragEle.dragStart()
        setTimeout(() => {
            dragEle.dragEnd()
            rej('时间已经到了哦，不能再继续移动了哦')
        }, 3000)
    }).then((res) => console.log(res)).catch(res => console.log(res))

</script>

</html>